package com.jf3q.securitydemo.utils;

import com.jf3q.securitydemo.dao.MenuMapper;
import com.jf3q.securitydemo.entity.Menu;
import com.jf3q.securitydemo.entity.Role;
import jakarta.servlet.FilterChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @author:xiaojie
 * @create: 2024-01-29 14:52
 * @Description:
 */
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    MenuMapper menuMapper;
    AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        //访问此url需要的权限

        //.requestMatchers("/","/loginError","/validcode","/toLogin","/login").permitAll()//匿名访问

        String requestUrl = ((FilterInvocation) object).getRequestUrl();//当前访问的那个url
        if (requestUrl.equals("/")|| requestUrl.equals("/loginError")||requestUrl.equals("/validcode")||requestUrl.equals("/toLogin")||requestUrl.equals("/login")) {
            return null;//访问白名单不需要权限
        }
        List<Menu> list = menuMapper.getAll();
        for (Menu menu : list) {
            //requestUrl   level1/1   /level1/**
            if (antPathMatcher.match(menu.getMpath(),requestUrl)) {
                List<Role> roles = menu.getRoles();//list   里面的role_code转成数组

                String[] roleStr= new String[roles.size()+1];//权限数组 （包含了角色  和菜单）
                for (int i = 0; i < roles.size(); i++) {
                    roleStr[i]=roles.get(i).getRoleCode();
                }

                roleStr[roles.size()]=menu.getMcode();
               return  SecurityConfig.createList(roleStr);
            }


        }


        //level4/8
        return SecurityConfig.createList("ROLE_login");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
